// 封装eventEmitter 发布订阅 

// emit 发布 
// on   订阅
// once 只订阅一次


// 定义接口
interface Listener {
    (...age: any[]): void
    fn?: Listener
}

interface Events {
    [eventName: string]: Listener[]
}

// 定义EventEmitter 类 

class EventEmitter {
    protected events: Events = {}  //protected受保护的

    // emit
    emit(eventName: string, ...args: any[]) {
        if (!this.events[eventName]) return false

        this.events[eventName].forEach((listener: Listener) => {
            return listener(...args)
        })

        return true
    }

    // on
    on(eventName: string, listener: Listener) {
        if (!this.events[eventName]) {
            this.events[eventName] = [listener]
        } else {
            this.events[eventName].push(listener)
        }

        return false
    }

    // once
    once(eventName: string, listener: Listener) {

        const on: Listener = (...args) => listener(...args)

        on.fn = listener;

        this.on(eventName, on)

        return this
    }
}


let req = new EventEmitter()

req.once('data',data=>{
    console.log(data);
    
})

req.emit('data',"123")